import { runTasksInParallel } from './handy.js';
import { initUser } from './user.js';
import { getContext } from './context.js';
import { CENSOR_TYPE_MAP } from './constants.js';
import { generateReport } from './report.js';
import { verify } from './baseInfo.js';
import { showToast } from './toast.js';

export async function analyze() {
    const verifyBaseInfoErrMsg = verify();
    if (typeof verifyBaseInfoErrMsg === 'string') {
        showToast('请先录入基本信息');
        return;
    }
    const context = getContext();
    context.isOperating = true;
    const analyzeStartTime = Date.now();
    console.log('开始分析');
    const fileList = context.fileList;
    console.log('文件列表: ', fileList);
    const zipFileHash = context.zipFileHash;
    // check if all pdf parse done
    for (let i = 0; i < fileList.length; i++) {
        const pdfFile = fileList[i];
        if (!pdfFile.imageList) {
            throw new Error('pdf解析失败：' + pdfFile.fileName);
        }
        if (!pdfFile.purpose) {
            throw new Error('文件用途分析失败：' + pdfFile.fileName);
        }
    }
    await censor.call(this, {
        zipFileHash,
        fileList,
    });
    // end
    const analyzeEndTime = Date.now();
    console.log('全部任务已完成');
    const analyzeDuration = analyzeEndTime - analyzeStartTime;
    console.log(`总耗时: ${analyzeDuration / 1000} 秒`);
    context.isOperating = false;
}

function getRelateFiles() {
    const context = getContext();
    const censorType = context.censorType;
    console.log('censorType: ', censorType);
    const pdfFileList = context.fileList;
    // collect relative files
    const relateFiles = [];
    const relateOcrFiles = [];
    const map = CENSOR_TYPE_MAP.find((e) => e.censorType == censorType);
    if (!map) {
        throw new Error('未找到对应的关联文件名目录');
    }
    const relateFileNames = map.relateFiles;
    const ocrFiles = map.ocrFiles;
    console.log('待OCR文件列表', ocrFiles);
    for (let i = 0; i < pdfFileList.length; i++) {
        const pdfFile = pdfFileList[i];
        const pdfFileName = pdfFile.purpose.fileName;
        for (let j = 0; j < relateFileNames.length; j++) {
            const relateFileName = relateFileNames[j];
            if (pdfFileName.includes(relateFileName)) {
                relateFiles.push(pdfFile);
            }
        }
        for (let k = 0; k < ocrFiles.length; k++) {
            const ocrFileInfo = ocrFiles[k];
            const ocrFileName = ocrFileInfo.fileName;
            const ocrType = ocrFileInfo.ocrType;
            if (pdfFileName.includes(ocrFileName)) {
                relateOcrFiles.push({ pdfFile, ocrType });
            }
        }
    }
    return { relateFiles, ocrFiles: relateOcrFiles };
}

async function ocr(pdfFile, ocrType) {
    const context = getContext();
    console.log('正在OCR文件: ' + pdfFile.fileName);
    context.censorStatus = '正在读取文件内容：' + pdfFile.fileName;
    const uuid = await initUser();
    const zipFileHash = context.zipFileHash;
    const pdfFileHash = pdfFile.hash;
    const formData = new FormData();
    formData.append('uuid', uuid);
    formData.append('zipFileHash', zipFileHash);
    formData.append('pdfFileHash', pdfFileHash);
    formData.append('ocrType', ocrType);
    const response = await fetch('/ocr', {
        method: 'post',
        body: formData,
    });
    const json = await response.json();
    if (json.code === 200) {
        const result = json.result;
        pdfFile.ocr = result.ocrResults;
        return;
    }
    console.error(JSON.stringify(json));
    if (json.code) {
        throw new Error('ocr失败: ' + json.message);
    }
    throw new Error('ocr失败: ', pdfFile);
}

async function censor() {
    const context = getContext();
    let { relateFiles, ocrFiles } = getRelateFiles.call(this);
    const tasks = [];
    for (const pdfFileInfo of ocrFiles) {
        const { pdfFile, ocrType } = pdfFileInfo;
        tasks.push(ocr.bind(this, pdfFile, ocrType));
    }
    let startTime = Date.now();
    await runTasksInParallel(tasks, 2);
    let duration = Date.now() - startTime;
    console.log(`OCR总耗时: ${duration / 1000} 秒`);
    console.log('OCRy文件列表: ', ocrFiles);
    console.log('相关文件: ', relateFiles);
    startTime = Date.now();
    await generateReport.call(this, { relateFiles });
    duration = Date.now() - startTime;
    console.log(`报告生成总耗时: ${duration / 1000} 秒`);
    context.isOperating = false;
    context.censorStatus = '';
}




